from rest_framework import serializers
from .models import User,Address,Feedback
import re
from django_redis import get_redis_connection


class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

# 地址管理
class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True,help_text="省份信息")  # 指向areas的model中的__str__字段
    city = serializers.StringRelatedField(read_only=True,help_text="城市信息")
    district = serializers.StringRelatedField(read_only=True,help_text="县城信息")
    province_id = serializers.IntegerField(label='省ID', required=True,help_text="省ID")
    city_id = serializers.IntegerField(label='市ID', required=True,help_text="城市ID")
    district_id = serializers.IntegerField(label='区ID', required=True,help_text="县城ID")

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存，这里跟update更新没有任何关系，仅仅是新建收货地址的的时候进行保存
        """
        validated_data['user'] = self.context['request'].user  # 地址表中以user作为外键，序列化器中exlude了user，所以这里要自己加上
        return super().create(validated_data)

class UserInfoSerializer(serializers.ModelSerializer):
    """
    个人信息
    """
    class Meta:
        model = User
        fields  = ('realname', 'mobile', 'gender', 'img_url')

class UserRealNameSerializer(serializers.ModelSerializer):
    """
    用户真实姓名修改
    """
    class Meta:
        model = User
        fields = ('realname','id')
        extra_kwargs={
            'realname':{
                'max_length':20,
                'required':True,
                'error_messages':{
                    'max_length':'真实姓名超过最大长度',
                }
            }
        }

class UserGenderSerializer(serializers.ModelSerializer):
    """
    用户性别修改
    """
    class Meta:
        model = User
        fields = ('gender_userinfo','id')
        extra_kwargs={
            'gender_userinfo':{
                'required':True,
            }
        }

class UserMobileSendSMSCodeSerializer(serializers.Serializer):
    """
    检测是否多次发送短信验证码
    """

    def validate(self, attrs):
        # redis中发送短信验证码的标志 send_flag_<mobile> : 1  由redis维护60s的有效期
        redis_conn = get_redis_connection('verify_codes')
        mobile = self.context['view'].kwargs.get('mobile')
        if mobile:
            send_flag = redis_conn.get('send_flag_%s' % mobile)
            if send_flag:
                raise serializers.ValidationError('发送短信次数过于频繁')
        return attrs

class UserMobileRegisterSerializer(serializers.ModelSerializer):
    """
    短信验证码校验
    """
    mobile = serializers.CharField(min_length=11,max_length=11,label="手机号码")
    sms_code = serializers.CharField(min_length=6,max_length=6,label="手机验证码")
    class Meta:
        model = User
        fields = ('id', 'mobile', 'sms_code')
        extra_kwargs = {
            'mobile': {
                'min_length': 11,
                'max_lenth': 11,
                'error_messages': {
                    'min_length': "手机号码长度必须为11位",
                    'max_length': "手机号码长度必须位11位",
                }
            },
            'sms_code': {
                'min_length': 6,
                'max_lenth': 6,
                'error_messages': {
                    'min_length': "请输入6位的验证码",
                    'max_length': "请输入6位的验证码",
                }
            }
        }

    def validate(self, attrs):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', attrs['mobile']):
            raise serializers.ValidationError('手机号格式错误')

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码无效')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')
        return attrs


# 意见反馈
class FeedBackSerializer(serializers.ModelSerializer):
    """
    意见反馈检验
    """

    class Meta:
        model = Feedback
        fields = ('suggestion_id','suggestion_text')

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user  # 地址表中以user作为外键，序列化器中exlude了user，所以这里要自己加上
        return super().create(validated_data)
